package com.tracesystem.security;

import com.fasterxml.jackson.databind.ObjectMapper;

import com.tracesystem.commons.Result;
import com.tracesystem.controller.info.SimpleUserInfo;
import com.tracesystem.dao.IssueResourceDao;
import com.tracesystem.util.WoniuCopyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

//    @Lazy
//    private ResourceDao resourceDao;
    @Autowired
    @Lazy
    private IssueResourceDao issueResourceDao;


    private ObjectMapper objectMapper =new ObjectMapper();

//    @Autowired
//    private ObjectRedisTemplate objectRedisTemplate;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf8");
        response.setCharacterEncoding("utf-8");
        SimpleUserInfo simpleUserInfo = WoniuCopyUtil.copyOne(authentication.getPrincipal(), SimpleUserInfo.class);
        List<String> list =issueResourceDao.getResourceUriList(simpleUserInfo.getRoleId());
        request.getSession().setAttribute("login_uri_resource",list);
        Result result = Result.getInstance(SimpleUserInfo.class).setData(simpleUserInfo).setMsg("登录成功");
        response.getWriter().write(objectMapper.writeValueAsString(result));

    }
}
